package tut.net.admage;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class NendAdnetworker extends Adnetworker{

	private static final String PROTOCOL_HTTP 	= "http://";
	private static final String PROTOCOL_HTTPS 	= "https://";
	
	private static final int _DELFLAG_ON 	= 2;
	private static final int _DELFLAG_OFF 	= 1;
	
	private String url = null;
	
	private String apiKey;
	private String format = "json";
	private int offset = 0;
	private int limit = 2000;
	private String date;
	private int time = -1;
	private int timeLength = -1;
	private int delFlg = 0;

	public NendAdnetworker(String apiKey, String url,String date, int time, int timeLength){
		super(apiKey, url, date);
		this.time = time;
		this.timeLength = timeLength;
	}
	
	//GET https://www.nend.net/api/report/media_adspot?api_key=abcdefghijk&date=2013-09-01&time=18&time_length=6hours&offset=0&limit=2000
	public String bulidRequestUrl(){
		StringBuilder requestUrl = new StringBuilder(this.url);
		//パラメータ追加
		requestUrl.append("?").append("api_key=").append(this.apiKey);
		requestUrl.append("&").append("date=").append(this.date);
		requestUrl.append("&").append("format=").append(this.format);
		
		if(time>=0)		requestUrl.append("&").append("time=").append(this.time);
		if(timeLength>0)requestUrl.append("&").append("time_length=").append(this.timeLength).append("hours");
		if(delFlg>0)	requestUrl.append("&").append("del_flg=").append(this.delFlg);
		
		requestUrl.append("&").append("offset=").append(this.offset);
		requestUrl.append("&").append("limit=").append(this.limit);
		
		return requestUrl.toString();
	}
	
	public String downloadReport() throws Exception{
		
		String json = sendGet();
		
		return json;
	}
	
	// https://hc.apache.org/httpcomponents-client-4.3.x/examples.html
	private String sendGet() throws Exception{
		 CloseableHttpClient httpclient = HttpClients.createDefault();
	        try {
	            HttpGet httpget = new HttpGet(this.bulidRequestUrl());
	            System.out.println("Executing request " + httpget.getRequestLine());

	            // Create a custom response handler
	            ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

	                public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
	                    int status = response.getStatusLine().getStatusCode();
	                    if (status >= 200 && status < 300) {
	                        HttpEntity entity = response.getEntity();
	                        return entity != null ? EntityUtils.toString(entity) : null;
	                    } else {
	                        throw new ClientProtocolException("Unexpected response status: " + status);
	                    }
	                }

	            };
	            
	            String responseBody = httpclient.execute(httpget, responseHandler);
	            System.out.println("----------------------------------------");
	            System.out.println(responseBody);
	            return responseBody;
	        } finally {
	            httpclient.close();
	        }
	}
	
	private String sendGetTest2() throws Exception {
		 
		String url = "http://www.google.com/search?q=mkyong";
 
		URL obj = new URL(url);
		HttpURLConnection con = (HttpURLConnection) obj.openConnection();
 
		// optional default is GET
		con.setRequestMethod("GET");
 
		int responseCode = con.getResponseCode();
		System.out.println("\nSending 'GET' request to URL : " + url);
		System.out.println("Response Code : " + responseCode);
 
		BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
		String inputLine;
		StringBuffer response = new StringBuffer();
 
		while ((inputLine = in.readLine()) != null) {
			response.append(inputLine);
		}
		in.close();
 
		//print result
		System.out.println(response.toString());
 
		return null;
	}
	
	public void makeHTTPPOSTRequest() {
        try {
        	String url = "";
        	String apiusername = "";
        	String apipassword = "";
            HttpClient c = new DefaultHttpClient();        
            HttpPost p = new HttpPost(url);        
 
            p.setEntity(new StringEntity("{\"username\":\"" + apiusername + "\",\"password\":\"" + apipassword + "\"}", ContentType.create("application/json")));
            //p.setEntity(new StringEntity("{\"username\":\"" + apiusername + "\",\"password\":\"" + apipassword + "\"}"));
            HttpResponse r = c.execute(p);
 
            BufferedReader rd = new BufferedReader(new InputStreamReader(r.getEntity().getContent()));
            String line = "";
            while ((line = rd.readLine()) != null) {
               //Parse our JSON response               
               JSONParser j = new JSONParser();
               JSONObject o = (JSONObject)j.parse(line);
               Map response = (Map)o.get("response");
 
               System.out.println(response.get("somevalue"));
            }
        }
        catch(ParseException e) {
            System.out.println(e);
        }
        catch(IOException e) {
            System.out.println(e);
        }                        
    }    
	
	
	public void sendGetTest() {
		String resString = "";
		BufferedReader in = null;
		try {
			HttpClient client = new DefaultHttpClient();
			String reqString = "";
			HttpGet method = new HttpGet(reqString);
			HttpResponse response = client.execute(method);
			in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			StringBuffer sb = new StringBuffer("");
			String line = "";
			String NL = System.getProperty("line.separator");
			while ((line = in.readLine()) != null) {
				sb.append(line + NL);
			}
			in.close();
			resString = sb.toString();
		} catch (Exception e) {
		}
	}

	// set and get method
	public int getOffset() {
		return offset;
	}

	public void setOffset(int offset) {
		this.offset = offset;
	}

	public int getLimit() {
		return limit;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}

	public int getTime() {
		return time;
	}

	public void setTime(int time) {
		this.time = time;
	}

	public int getTimeLength() {
		return timeLength;
	}

	public void setTimeLength(int timeLength) {
		this.timeLength = timeLength;
	}
	
}
